package com.chuji.crmcj.act;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.TurnoverYesOrNoInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.chuji.crmcj.view.CalendarView;
import com.chuji.crmcj.view.CalendarViewDialog;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderWriteActivity extends BaseActivity implements View.OnClickListener {
    //返回
    private ImageView mIv_Back;
    //判断是现场成交还是跟进成交
    List<TurnoverYesOrNoInfo.ApiParamObjEntity> turnoverYesOrNoData;
    private TurnoverYesOrNoInfo turnoverYesOrNoInfo;
    private TextView tv_turnover;
    //选择汽车类型
    private LinearLayout mLl_turnover_type;
    private TextView mTv_turnover_type;
    //用户选择
    String car_type;
    //选择汽车配置
    private LinearLayout mLl_turnover_configure;
    private TextView mTv_turnover_configure;
    //用户选择
    String car_configure;
    //选择汽车颜色
    private LinearLayout mLl_turnover_color;
    private TextView mTv_turnover_color;
    //用户选择
    String car_color;
    //车架号
    private EditText mEt_frame_num;
    String frame_num;
    //用户选择的日期
    private TextView mTv_data;
    //日历
    private ImageView mIv_calendar;
    //用户输入的成交金额
    private EditText mEt_turnover_money;
    String turnover_money;
    //成交方式选择
    private LinearLayout mLl_turnover_way;
    private TextView mTv_turnover_way;
    //用户选择
    String turnover_way;
    //支付方式选择
    private LinearLayout mLl_pay_way;
    private TextView mTv_pay_way;
    //用户选择
    String payer_way;
    //汽车使用者的名字
    private EditText mEt_car_user_name;
    String user_name;
    //客户身份证号
    private EditText mEt_id_num;
    String id_num;
    //提交
    private Button mBtn_submit;
    //适配器
    ArrayAdapter<String> adapter;
    //管理器
    WindowManager windowManager;
    //自定义dialog
    CalendarViewDialog dialog;
    WindowManager.LayoutParams lp;
    //当前日期
    String date;
    private String addString = ",";

    private static final String TAG = OrderWriteActivity.class.getSimpleName();
    //意图
    private Intent mIntent;
    //请求码
    private int requestCode;
    //客户ID
    String CustomerID;
    //客流ID
    String FlowID;
    //销售员ID
    String SalesID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_write);
        //初始化组件
        tv_turnover = (TextView) findViewById(R.id.tv_turnover);
        mTv_turnover_type = (TextView) findViewById(R.id.tv_turnover_type);
        mTv_turnover_configure = (TextView) findViewById(R.id.tv_turnover_configure);
        mTv_turnover_color = (TextView) findViewById(R.id.tv_turnover_color);
        mTv_turnover_way = (TextView) findViewById(R.id.tv_turnover_way);
        mTv_pay_way = (TextView) findViewById(R.id.tv_pay_way);
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        mLl_turnover_type = (LinearLayout) findViewById(R.id.ll_turnover_type);
        mLl_turnover_configure = (LinearLayout) findViewById(R.id.ll_turnover_configure);
        mLl_turnover_color = (LinearLayout) findViewById(R.id.ll_turnover_color);
        mEt_frame_num = (EditText) findViewById(R.id.et_frame_num);
        mTv_data = (TextView) findViewById(R.id.tv_data);
        mIv_calendar = (ImageView) findViewById(R.id.iv_calendar);
        mEt_turnover_money = (EditText) findViewById(R.id.et_turnover_money);
        mLl_turnover_way = (LinearLayout) findViewById(R.id.ll_turnover_way);
        mLl_pay_way = (LinearLayout) findViewById(R.id.ll_pay_way);
        mEt_car_user_name = (EditText) findViewById(R.id.et_car_user_name);
        mEt_id_num = (EditText) findViewById(R.id.et_id_num);
        mEt_frame_num = (EditText) findViewById(R.id.et_frame_num);
        mTv_data = (TextView) findViewById(R.id.tv_data);
        mIv_calendar = (ImageView) findViewById(R.id.iv_calendar);
        mEt_turnover_money = (EditText) findViewById(R.id.et_turnover_money);
        mEt_car_user_name = (EditText) findViewById(R.id.et_car_user_name);
        mEt_id_num = (EditText) findViewById(R.id.et_id_num);
        mBtn_submit = (Button) findViewById(R.id.btn_upload_code);
        //弹出数字键盘
        mEt_turnover_money.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        mEt_id_num.setInputType(EditorInfo.TYPE_CLASS_PHONE);
//        //设置金额输入监听
//        mEt_turnover_money.addTextChangedListener(mTextWatcher);
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        date = sdf.format(new Date());
        mTv_data.setText(date);
        //获取ID
        mIntent = getIntent();
        CustomerID = mIntent.getStringExtra("CustomerID");
//        FlowID=mIntent.getStringExtra("FlowID");
        SalesID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        //设置点击监听
        mLl_turnover_type.setOnClickListener(this);
        mLl_turnover_configure.setOnClickListener(this);
        mLl_turnover_color.setOnClickListener(this);
        mLl_turnover_way.setOnClickListener(this);
        mLl_pay_way.setOnClickListener(this);
        //返回
        mIv_Back.setOnClickListener(this);
        mIv_calendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog = new CalendarViewDialog(OrderWriteActivity.this);
                dialog.show();
                dialog.calendar.setOnItemClickListener(new CalendarView.OnItemClickListener() {
                    @Override
                    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
                        if (dialog.calendar.isSelectMore()) {
                            UIUtils.showToastSafe(dialog.format.format(selectedStartDate) + "到" + dialog.format.format(selectedEndDate));
                        } else {
                            mTv_data.setText(dialog.format.format(downDate));
                            dialog.dismiss();
                        }
                    }
                });
                windowManager = getWindowManager();
                lp = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
                //p.height = (int) (d.getHeight() * 0.3);   //高度设置为屏幕的0.3
                lp.width = windowManager.getDefaultDisplay().getWidth();//为获取屏幕宽、高,宽度设置为全屏
                dialog.getWindow().setAttributes(lp);     //设置生效
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        getData();
        //提交数据
        mBtn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //得到用户输入的数据
                frame_num = mEt_frame_num.getText().toString();
                turnover_money = mEt_turnover_money.getText().toString();
                user_name = mEt_car_user_name.getText().toString();
                id_num = mEt_id_num.getText().toString();
                if (!frame_num.equals("") && !turnover_money.equals("") && !user_name.equals("") && !id_num.equals("") && !car_type.equals("未选择") && !car_configure.equals("未选择") && !car_color.equals("未选择") && !turnover_way.equals("未选择") && !payer_way.equals("未选择")) {
                    showSubmitOrderDialog();
                } else {
                    UIUtils.showToastSafe("订单未填完");
                }
            }
        });
    }

    //请求参数判断是现场成交还是跟进成交
    public void getData() {
        //第一次
        if (turnoverYesOrNoData == null) {
            turnoverYesOrNoData = new ArrayList<TurnoverYesOrNoInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_TURN_OR_FOLLOW + "&CustomerID=" + CustomerID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                turnoverYesOrNoInfo = JSON.parseObject(response, TurnoverYesOrNoInfo.class);
                if (turnoverYesOrNoInfo.getApiParamObj().size() != 0) {
                    turnoverYesOrNoData.addAll(turnoverYesOrNoInfo.getApiParamObj());
                    UIUtils.runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            if (turnoverYesOrNoData.get(0).getNum().equals("1")) {
                                tv_turnover.setText("现场成交");
                            } else {
                                tv_turnover.setText("跟进成交");
                            }
                        }
                    });
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //订单车型返回数据
        String type = data.getStringExtra("type");
        //订单配置返回数据
        String configure = data.getStringExtra("configure");
        //订单颜色返回数据
        String color = data.getStringExtra("color");
        //成交方式返回数据
        String turnover = data.getStringExtra("turnover");
        //付款方式返回数据
        String payway = data.getStringExtra("payway");

        // 根据上面发送过去的请求码来区别
        switch (requestCode) {
            case 0:
                mTv_turnover_type.setText(type);
                car_type = mTv_turnover_type.getText().toString();
                break;
            case 1:
                if (configure.equals("")) {
                    mTv_turnover_configure.setText("未填写");
                } else {
                    mTv_turnover_configure.setText(configure);
                    car_configure = mTv_turnover_configure.getText().toString();
                }
                break;
            case 2:
                if (color.equals(" ")) {
                    mTv_turnover_color.setText("未填写");
                } else {
                    mTv_turnover_color.setText(color);
                    car_color = mTv_turnover_color.getText().toString();
                }
                break;
            case 3:
                if (turnover.equals(" ")) {
                    mTv_turnover_way.setText("未填写");
                } else {
                    mTv_turnover_way.setText(turnover);
                    turnover_way = mTv_turnover_way.getText().toString();
                }
                break;
            case 4:
                if (payway.equals(" ")) {
                    mTv_pay_way.setText("未填写");
                } else {
                    mTv_pay_way.setText(payway);
                    payer_way = mTv_pay_way.getText().toString();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.ll_turnover_type:
                //跳转到成交类型界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), TurnoverTypeActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 0;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_turnover_configure:
                //跳转到成交配置界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), CarConfigureActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 1;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_turnover_color:
                //跳转到成交颜色界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), CarColorActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 2;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_turnover_way:
                //跳转到成交方式界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), TurnoverWayActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 3;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_pay_way:
                //跳转到付款方式界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), PayWayActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 4;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.iv_Back:
                showCancelOrderDialog();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    //系统返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)

        {
            showCancelOrderDialog();
        }
        return false;
    }

    private void showSubmitOrderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_submit_order, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tv_turnover.getText().toString() == "跟进成交") {
                    //提交数据
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("CustomerID", CustomerID);
//                    map.put("FlowID",FlowID);
                    map.put("CarModel", car_type);
                    map.put("CarConfiguration", car_configure);
                    map.put("CarColor", car_color);
                    map.put("VIN", frame_num);
                    map.put("DeliveryTime", mTv_data.getText().toString());
                    map.put("BargainType", turnover_way);
                    map.put("Amount", turnover_money);
                    map.put("PaymentType", payer_way);
                    map.put("UserName", user_name);
                    map.put("Card", id_num);
                    map.put("SalesID", SalesID);
                    map.put("IsTaskRecord", "1");
                    postRequest(UrlUtils.SUBMIT_TURNOVER_INFO, map, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            UIUtils.showToastSafe("提交成功");
                            finish();
                        }
                    });
                } else {
                    //提交数据
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("CustomerID", CustomerID);
//                    map.put("FlowID",FlowID);
                    map.put("CarModel", car_type);
                    map.put("CarConfiguration", car_configure);
                    map.put("CarColor", car_color);
                    map.put("VIN", frame_num);
                    map.put("DeliveryTime", mTv_data.getText().toString());
                    map.put("BargainType", turnover_way);
                    map.put("Amount", turnover_money);
                    map.put("PaymentType", payer_way);
                    map.put("UserName", user_name);
                    map.put("Card", id_num);
                    map.put("SalesID", SalesID);
                    map.put("IsTaskRecord", "0");
                    postRequest(UrlUtils.SUBMIT_TURNOVER_INFO, map, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            UIUtils.showToastSafe("提交成功");
                            finish();
                        }
                    });
                }
//            UIUtils.showToastSafe("用户的输入信息如下：车型："+car_type+"，配置："+car_configure+"，颜色："+car_color+"，成交方式："+turnover_way+"，支付方式："+payer_way+"，车架号："+
//            frame_num+"成交金额："+turnover_money+"万"+",交车日期："+mTv_data.getText().toString());
////                finish();
                dialog.dismiss();

            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void showCancelOrderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_cancel_order, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        private CharSequence temp;
        int beforeLen = 0;
        int afterLen = 0;
        int i;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            temp = s;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            beforeLen = s.length();
        }

        @Override
        public void afterTextChanged(Editable s) {
            String txt = mEt_turnover_money.getText().toString();
            afterLen = txt.length();

            if (afterLen > beforeLen) {
                if (txt.length() == 4) {
                    mEt_turnover_money.setText(new StringBuffer(txt).insert(
                            txt.length() - 3, ",").toString());
                    mEt_turnover_money.setSelection(mEt_turnover_money.getText()
                            .length());
                } else if (txt.length() == 6) {
                    mEt_turnover_money.setText(new StringBuffer(txt).replace(2, 2, "").toString());
                    mEt_turnover_money.setText(new StringBuffer(txt).insert(
                            txt.length() - 3, ",").toString());
                    mEt_turnover_money.setSelection(mEt_turnover_money.getText()
                            .length());
                }
            } else {
                if (txt.startsWith(" ")) {
                    mEt_turnover_money.setText(new StringBuffer(txt).delete(
                            afterLen - 1, afterLen).toString());
                    mEt_turnover_money.setSelection(mEt_turnover_money.getText()
                            .length());
                }
            }
        }
    };
}
